<?php

namespace app\common\model\virtual;


use app\common\model\BaseModel;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;

/**
 * 前端扫码,临时记录表
 * Class ScanTempLog
 * @package app\model
 */
class VirtualScanTempLogModel extends BaseModel
{
    //
    public string $fieldOrderNo = 'order_no';

    // 订单号
    public string $fieldMerId = 'mer_id';
    // 商户编号
    public string $fieldVpId = 'vp_id';
    // 活动ID
    public string $fieldUserId = 'user_id';
    // 导购ID
    public string $fieldProductCode = 'product_code';
    // 商品码
    public string $fieldNum = 'num';
    // 已扫数
    public string $fieldUpdateAt = 'update_at';
    // 更新时间
    protected $name = 'virtual_scan_temp_log';

    // 设置字段信息
    protected $schema = [
        'order_no' => 'string',        // 订单号
        'mer_id' => 'string',        // 商户编号
        'vp_id' => 'int',        // 活动ID
        'user_id' => 'int',        // 导购ID
        'product_code' => 'string',        // 商品码
        'num' => 'int',        // 已扫数
        'update_at' => 'datetime',        // 更新时间
    ];

    /**
     *
     * @param array $params
     */
    public function insterSave(array $params): void
    {
        $sql = 'insert into t_virtual_scan_temp_log (order_no,mer_id,vp_id,user_id,product_code,num,vp_num)
values(\'%s\',\'%s\',%d,%d,\'%s\',%d,%d) ON CONFLICT(order_no, product_code) do update set num = t_virtual_scan_temp_log.num+ 1';
        $sql = sprintf($sql, (string)$params['order_no'], (string)$params['mer_id'], (int)$params['vp_id'], (int)$params['user_id'], (string)$params['product_code'], (int)($params['num'] ?? 1),(int)($params['vp_num']));
        $this->db()->batchQuery([$sql]);
    }


    /**
     * 获取订单信息
     * @param array $params
     * @param  $filed
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function list(array $params ,  $filed = '*'): array
    {
        return $this->db()->where($params)->field($filed)
            ->select();
    }

    public function valiProduct($order , $product_code){
       $data  =  $this->db()->where(['order_no' => $order , 'product_code' => $product_code])->find();
       if (!empty($data) && $data['num'] + 1 > $data['vp_num']) {
           throw  new Exception('该商品数量已达标，请扫描未达标商品',API_ERROR);
       }
    }
}
